# -*- coding:utf-8 -*-

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from downloader import *
from myscrollarea import *

class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        QMainWindow.__init__(self,parent)
        self.settings = QSettings("PyDilbert","pydilbert")
        self.statusbar = QStatusBar();
        self.toolbar = QToolBar("Main Toolbar")
        self.toolbar.setObjectName("toolbar")
        self.imageLabel = QLabel();
        self.scrollArea = MyScrollArea();
        self.downloader = Downloader();
        self.progress = QProgressBar();
        self.comicDate = QDate.currentDate();
        self.calendarAct,self.prevDayAct,self.todayAct,self.nextDayAct,self.saveAct,self.printAction = (QAction,QAction,QAction,QAction,QAction,QAction)
        self.calendar = QCalendarWidget(self.scrollArea)

        self.calendar.setGridVisible(True)
        self.calendar.setMinimumDate(QDate(1996,11,24))
        self.calendar.setMaximumDate(QDate.currentDate())
        self.calendar.hide()

        self.setupToolBar()
        self.setupActions()
        self.setupStatusBar()
        self.setupMainWindow()

#        self.connect(self.calendarAct,SIGNAL("triggered(bool)"),self.showOrHideCalendar)
        self.connect(self.prevDayAct,SIGNAL("triggered(bool)"),self.getPrevDay)
        self.connect(self.todayAct,SIGNAL("triggered(bool)"),self.getToday)
        self.connect(self.nextDayAct,SIGNAL("triggered(bool)"),self.getNextDay)
        self.connect(self.saveAct,SIGNAL("triggered(bool)"),self.saveComic)
        self.connect(self.printAct,SIGNAL("triggered(bool)"),self.printComic)

        self.connect(self.downloader,SIGNAL("done(bool)"),self.loadComic)
        self.connect(self.downloader,SIGNAL("updateProgress(int,int)"),self.updateProgress)
        self.connect(self.downloader,SIGNAL("started()"),self.updateStatusBar)
        self.connect(self.downloader,SIGNAL("gotError(const QString&)"),self.showErrorMessage)

        self.connect(self.calendar,SIGNAL("clicked(const QDate&)"),self.dateSelected)
        self.connect(self.scrollArea,SIGNAL("clicked()"),self.calendar.hide)

        self.applySettings()

        # Grab today's comic
        self.getToday()

    def contextMenuEvent(self,event):
        menu = QMenu(self)
        menu.addAction(self.saveAct)
        menu.addAction(self.printAct)
        menu.exec_(event.globalPos())

    def setupStatusBar(self):
        self.statusbar.setSizeGripEnabled(False)
        self.statusbar.showMessage("Daily Dilbert")
        self.statusbar.addPermanentWidget(self.progress)
        self.progress.hide()

    def setupToolBar(self):
        self.toolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.prevDayAct = self.toolbar.addAction(QIcon(":/images/prev.png"), self.tr("&Previous Day"))
        self.todayAct = self.toolbar.addAction(QIcon(":/images/home.png"), self.tr("&Today's Dilbert"))
        self.nextDayAct = self.toolbar.addAction(QIcon(":/images/next.png"), self.tr("&Next Day"))
#        self.calendarAct = self.toolbar.addAction(QIcon(":/images/date.png"), self.tr("&Show calendar..."))
        self.saveAct = self.toolbar.addAction(QIcon(":/images/save.png"), self.tr("&Save..."))
        self.printAct = self.toolbar.addAction(QIcon(":/images/print.png"), self.tr("&Print..."))

    def setupActions(self):
        self.nextDayAct.setEnabled(False)
        self.saveAct.setEnabled(False)
        self.printAct.setEnabled(False)

    def setupMainWindow(self):
        self.imageLabel.setBackgroundRole(QPalette.Base)
        self.scrollArea.setBackgroundRole(QPalette.Dark)
        self.scrollArea.setWidget(self.imageLabel)

        self.resize(650,275)
        self.addToolBar(self.toolbar)
        self.setWindowTitle("Daily Dilbert")
        self.setCentralWidget(self.scrollArea)
        self.setStatusBar(self.statusbar)

    def applySettings(self):
        self.settings.beginGroup("MainWindow")
        self.restoreState((self.settings.value("State")).toByteArray())
        self.settings.endGroup()

    def closeEvent(self,event):
        self.settings.beginGroup("MainWindow");
        self.settings.setValue("State", QVariant(self.saveState()))
        self.settings.endGroup()

    def loadComic(self,error):
        if not error:
            if self.comicDate == QDate.currentDate():
                self.statusbar.showMessage(self.tr("Today's Dilbert"))
            else:
                self.statusbar.showMessage("Dilbert - %s" % unicode(self.comicDate.toString(Qt.TextDate)))

            imageData = self.downloader.getImageData();

            image = QImage()
            image.loadFromData(imageData)
            self.imageLabel.setPixmap(QPixmap.fromImage(image))
            self.imageLabel.adjustSize()

            if self.toolbar.orientation() == Qt.Horizontal:
                self.resize(image.width()+10, image.height()+self.toolbar.height()+35)
            else:
                self.resize(image.width()+self.toolbar.width()+10, image.height()+35)

            self.saveAct.setEnabled(True)
            self.printAct.setEnabled(True)

        self.todayAct.setEnabled(True)
        self.prevDayAct.setEnabled(True)
        self.nextDayAct.setEnabled(self.comicDate < QDate.currentDate())

    def saveComic(self):
        s = QFileDialog.getSaveFileName(self,
                                        self.tr("Save Comic - Daily Dilbert"),
                                        QDir.homePath()+"/dilbert-"+self.comicDate.toString(Qt.ISODate)+".jpeg",
                                        self.tr("Image: (*.jpg)"))
        if not s.isEmpty():
            saveFile = QFile(s)
            saveFile.open(QIODevice.WriteOnly)
            saveFile.write(self.downloader.getImageData())
            saveFile.close()

    def printComic(self):
        printer = QPrinter(QPrinter.ScreenResolution)
        printer.setOutputFileName("dilbert-"+self.comicDate.toString(Qt.ISODate)+".pdf")

        dialog = QPrintDialog(printer, self)
        dialog.setWindowTitle(self.tr("Print Document"))

        if (dialog.exec_() == QDialog.Accepted):
            painter = QPainter()
            painter.begin(printer)
            image = QImage()
            image.loadFromData(self.downloader.getImageData())

            painter.drawImage(QRectF(0,0,image.width(),image.height()),image)
            painter.end()

    def updateProgress(self,done,total):
        if done < total:
            value = round((float(done)/float(total))*100, 0)
            self.progress.setValue(value)
        else:
            self.progress.setValue(0)
            self.progress.hide()

    def updateStatusBar(self):
        self.todayAct.setEnabled(False);
        self.prevDayAct.setEnabled(False);
        self.nextDayAct.setEnabled(False);
        self.saveAct.setEnabled(False);
        self.printAct.setEnabled(False);

        self.progress.show()
        self.statusbar.showMessage(self.tr("Downloading comic"))

    def enableActions(self):
        self.todayAct.setEnabled(True);
        self.prevDayAct.setEnabled(True);
        self.nextDayAct.setEnabled(True);

    def getPrevDay(self):
        self.comicDate = self.comicDate.addDays(-1)
        self.downloader.download(self.comicDate)

    def getToday(self):
        self.comicDate = QDate.currentDate()
        self.downloader.download(self.comicDate)

    def getNextDay(self):
        self.comicDate = self.comicDate.addDays(1)
        self.downloader.download(self.comicDate)

    def showErrorMessage(self,error):
        self.progress.setValue(0)
        self.progress.hide()
        self.statusbar.showMessage("Daily Dilbert")
        QMessageBox.critical(self,self.tr("An Error Occurred!"),error)
        self.enableActions()

    def showOrHideCalendar(self):
        if self.calendar.isVisible():
            self.calendar.hide()
        else:
            self.calendar.show()

    def dateSelected(self,date):
        self.comicDate = QDate(date)
        self.calendar.hide()
        self.downloader.download(date)
